package Internet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;

public class TCPEchoServer {
    private ServerSocket serverSocket = null;

    public TCPEchoServer(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");

        //使用线程池进行多个客户端与服务器交互
        ExecutorService executorService = Executors.newCachedThreadPool();//线程数目动态增长

        while (true) {

            //接收到一个客户端
            Socket clientSocket = serverSocket.accept();

            //使用线程池
            executorService.submit(() -> {
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });

//            //使用多线程处理多个客户端请求
//            Thread thread = new Thread(() -> {
//                try {
//                    processConnection(clientSocket);
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//            });

//            //处理一个客户端的请求
//            //一次只能处理一个客户端请求
//            processConnection(clientSocket);
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s, %s] 客户端上线\n", clientSocket.getInetAddress(), clientSocket.getPort());

        try (InputStream inputStream = clientSocket.getInputStream();
                OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true) {
                if (!scanner.hasNext()) {
                    System.out.printf("[%s, %s] 客户端下线\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }

                //输入请求
                String request = scanner.next();

                //处理请求
                String response = process(request);

                //返回响应
                writer.println(response);
                //响应会存在缓冲区，需要刷新缓冲区，将响应发送出去
                writer.flush();

                //打印日志
                System.out.printf("[%s, %s] request: %s, response: %s\n", clientSocket.getInetAddress(), clientSocket.getPort(), request, response);
            }
        } finally {
            clientSocket.close();
        }

    }

    //处理请求
    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoServer tcpEchoServer = new TCPEchoServer(9090);
        tcpEchoServer.start();
    }
}
